﻿using GalaSoft.MvvmLight;
using IkeCode.WP7.HQReader.Model;
using System.Net;
using System.Windows;
using System.Linq;
using System.IO;
using System.Xml;
using IkeCode.WP7.HQReader.Interfaces;
using IkeCode.WP7.HQReader.Base;
using GalaSoft.MvvmLight.Ioc;
using System.Collections.Generic;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Windows.Input;
using IkeCode.WP7.Toolkit.Base;
using IkeCode.WP7.Toolkit.Base.Navigation;
using Microsoft.Phone.Shell;
using IkeCode.WP7.Toolkit.Helpers;
using IkeCode.WP7.Toolkit;
using System.Windows.Navigation;

namespace IkeCode.WP7.HQReader.ViewModel
{
    /// <summary>
    /// View Model for Main Page
    /// </summary>
    public class MainViewModel : BaseViewModel
    {
        #region ## Services ##

        private readonly IFeedPublisherDataService _publisherDataService;

        #endregion ## Services ##

        #region ## Properties ##

        /// <summary>
        /// Self Uri
        /// </summary>
        public override Uri MyUri
        {
            get
            {
                return new Uri("/Views/MainPage.xaml", UriKind.RelativeOrAbsolute);
            }
        }

        private List<IIcFeedPublisher> _listFeedPublishers = new List<IIcFeedPublisher>();
        /// <summary>
        /// List of IIcFeedPublisher
        /// </summary>
        public List<IIcFeedPublisher> ListFeedPublishers
        {
            get { return _listFeedPublishers; }
            set
            {
                if (_listFeedPublishers == value)
                {
                    return;
                }

                _listFeedPublishers = value;
                this.RaisePropertyChanged("ListFeedPublishers");
            }
        }

        #endregion ## Properties ##

        /// <summary>
        /// Constructor with IoC Services
        /// </summary>
        /// <param name="publisherDataService">Publisher Data Service</param>
        public MainViewModel(IFeedPublisherDataService publisherDataService)
        {
            _publisherDataService = publisherDataService;
            this.PageTitle = "Publishers";
            this.BindDesignData();

#if DEBUG
            var item1 = new IcFeedPublisherModel(new Uri("http://vidadeprogramador.com.br/feed/"), "Vida de Programador", 10);
            _publisherDataService.PostPublisher(item1, (pub, ex) =>
            {
                if (ex != null)
                {
                    return;
                }
                else
                {
                    var item2 = new IcFeedPublisherModel(new Uri("http://blog.drpepper.com.br/feed/"), "Dr Pepper", 5);
                    _publisherDataService.PostPublisher(item2, (pub2, ex2) =>
                    {
                        if (ex != null)
                        {
                            return;
                        }
                        else
                        {
                            this.Initialize();
                        }
                    });
                }
            });
#endif

#if !DEBUG
            this.Initialize();
#endif

            this.RegisterReloadView<MainViewModel>();
        }
        #region ## Commands ##

        /// <summary>
        /// Command to send the publisher to FeedPage
        /// </summary>
        public ICommand CommandToFeed
        {
            get
            {
                return new RelayCommand((param) =>
                {
                    var obj = (IIcFeedPublisher)param;
                    if (obj != null)
                    {
                        this.NavigateTo<FeedViewModel>();
                        Messenger.Default.Send<IIcFeedPublisher>(obj, "FeedList");
                    }
                });
            }
        }

        /// <summary>
        /// Command to Publisher Manager
        /// </summary>
        public override ICommand ManagerCommand
        {
            get
            {
                return new RelayCommand((param) =>
                {
                    var isUpdate = param is IIcFeedPublisher;
                    IIcFeedPublisher publisher = null;
                    this.NavigateTo<PublisherManagerViewModel>();

                    if (isUpdate)
                    {
                        publisher = (IIcFeedPublisher)param;
                    }

                    Messenger.Default.Send<IIcFeedPublisher>(publisher);
                });
            }
        }

        /// <summary>
        /// Command to remove selected publisher
        /// </summary>
        public override ICommand RemoveCommand
        {
            get
            {
                return new RelayCommand((param) =>
                {
                    if (param != null)
                    {
                        IIcFeedPublisher publisher = (IIcFeedPublisher)param;
                        if (publisher != null)
                        {
                            _publisherDataService.DeletePublisher(publisher, (success, error) =>
                            {
                                if (error != null)
                                {
                                    MessageBox.Show("Error occurred!");
                                }
                                else if (success)
                                {
                                    MessageBox.Show("Publisher successfully deleted!");
                                    this.ReloadView();
                                    this._navigationService.GoBack();
                                }
                            }, true);

                        }
                    }
                });
            }
        }

        /// <summary>
        /// Reload command
        /// </summary>
        public override ICommand ReloadCommand
        {
            get
            {
                return new RelayCommand((param) =>
                {
                    this.Initialize();
                });
            }
        }

        /// <summary>
        /// PinUnpin command
        /// </summary>
        public override ICommand PinUnpinCommand
        {
            get
            {
                return new RelayCommand((param) =>
                {
                    var publisher = (IIcFeedPublisher)param;
                    if (publisher != null)
                    {
                        var feedVm = SimpleIoc.Default.GetInstance<FeedViewModel>();
                        var uri = new Uri(string.Format("{0}?publisherId={1}", feedVm.MyUri, publisher.Id), UriKind.RelativeOrAbsolute);

                        if (publisher.IsPinned)
                        {
                            IcTileHelper.UnpinTile(uri);
                            publisher.IsPinned = false;
                        }
                        else
                        {
                            IcTileHelper.PinTile(uri, publisher.Title, publisher.Title, string.Empty, publisher.NewestCount);
                            publisher.IsPinned = true;
                        }

                        _publisherDataService.PostPublisher(publisher, (pubResult, e) =>
                        {

                        });
                    }
                });
            }
        }

        #endregion ## Commands ##

        #region ## Overrides ##

        /// <summary>
        /// Reload view
        /// </summary>
        protected override void ReloadView()
        {
            base.ReloadView();
            this.Initialize();
        }

        #endregion ## Overrides ##

        #region ## Private Methods ##

        private void BindDesignData()
        {
            if (this.IsInDesignMode)
            {
                _publisherDataService.GetPublishers((publishers, ex) =>
                {
                    publishers.ForEach(i => i.DefaultActionCommand = this.CommandToFeed);

                    this.ListFeedPublishers = publishers;
                });
            }
        }

        private void Initialize()
        {
            _publisherDataService.GetPublishers((publishers, ex) =>
            {
                if (ex != null)
                {
                    this._loadingService.SetReloadCommand(this.ReloadCommand, true);
                }
                else
                {
                    publishers.ForEach(i => i.DefaultActionCommand = this.CommandToFeed);
                    this.ListFeedPublishers = publishers;
                }
            });
        }

        #endregion ## Private Methods ##
    }
}